package com.example.boot.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.AopLogs;
import com.example.common.LogAnno;
import com.example.common.Result;
import com.example.common.enums.KeyEnum;
import com.example.common.enums.LogType;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.CustomException;
import com.example.context.BaseContext;
import com.example.pojo.dto.PasswordDTO;
import com.example.pojo.entity.Admin;
import com.example.pojo.utils.LoginUser;
import com.example.service.AdminService;
import com.example.utils.BCryptPasswordEncoderUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 管理员前端操作接口
 **/
@RestController
@RequestMapping("/admin")
@Api(tags = "用户接口")
public class AdminController {

    @Resource
    private AdminService adminService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增
     */
    @ApiOperation("新增用户信息")
    @LogAnno(title = "用户管理", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@ApiParam("用户信息") @RequestBody Admin admin) {
        adminService.add(admin);
        return Result.success();
    }

    /**
     * 删除
     */
    @ApiOperation("根据ID删除用户信息")
    @LogAnno(title = "用户管理", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@ApiParam("用户ID") @PathVariable Integer id) {
        adminService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @ApiOperation("根据ID批量删除信息")
    @LogAnno(title = "用户管理", type = LogType.DELBATCH)
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@ApiParam("用户信息集合") @RequestBody List<Integer> ids) {
        adminService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 修改
     */
    @ApiOperation("修改用户信息")
    @AopLogs(operation = "用户", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result updateById(@ApiParam("需要修改用户信息") @RequestBody Admin admin) {
        adminService.updateAdmin(admin);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @ApiOperation("根据ID查询用户信息")
    @GetMapping("/selectById/{id}")
    public Result selectById(@ApiParam("用户ID") @PathVariable Integer id) {
        Admin admin = adminService.selectById(id);
        return Result.success(admin);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(Admin admin ) {
        List<Admin> list = adminService.selectAll(admin);
        return Result.success(list);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(Admin admin,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Admin> page = adminService.selectPage(admin, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 根据用户id集合获取对应数据
     */
    @GetMapping("/getByIds")
    public Result getByPageIds(String ids,
                               String name,
                               @RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Admin> page = adminService.getByPageIds(ids, name, pageNum, pageSize);
        return Result.success(page);
    }

    @GetMapping("/logout")
    public Result logout(){
        //获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        if (!ObjectUtil.isEmpty(loginUser)){
            Integer userId = loginUser.getAdmin().getId();
            Boolean flag = redisTemplate.delete(KeyEnum.TOKEN + "_" + userId);
            if (flag) {
                return Result.success("退出成功");
            }

            return Result.error("400", "退出失败");
        }

        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    @LogAnno(title = "用户管理", type = LogType.UPDATE)
    public Result updatePassword(@RequestBody PasswordDTO passwordDTO) {
        Admin dbAdmin = adminService.selectById(passwordDTO.getId());
        if (ObjectUtil.isNull(dbAdmin)) {
            return Result.error(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!BCryptPasswordEncoderUtils.matchPassword(passwordDTO.getPasswordOld(), dbAdmin.getPassword())) {
            return Result.error(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        if (!StringUtils.hasLength(passwordDTO.getPasswordNew()) || !StringUtils.hasLength(passwordDTO.getPasswordOld())){
            return Result.error(ResultCodeEnum.PARAM_ERROR);
        }
        if (passwordDTO.getPasswordOld().equals(passwordDTO.getPasswordNew())) {
            return Result.error(ResultCodeEnum.PASSWORD_SAME_ERROR);
        }
        adminService.updatePassword(dbAdmin, passwordDTO);
        return Result.success();
    }

}
